<?php

namespace App\Models\Auth;

use App\Http\Traits\QueryHelperTrait;
use App\Models\Instructor\Instructor;
use App\Models\Permission\Role;
use App\Models\Permission\UserRole;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable, QueryHelperTrait;

    protected $fillable = [
        'first_name', 'last_name', 'username', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
    ];

    protected $appends = [
        'name',
    ];

    public function getNameAttribute() {
        return $this->first_name . ' ' . $this->last_name;
    }

    /* Relationship Start */
    public function accessTokens() {
        return $this->hasMany(OauthAccessToken::class);
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, UserRole::class);
    }
    /* Relationship End */

    /* API Start */
    public function updatePassword($password) {
        $this->password = Hash::make($password);
        $this->save();
    }

    /**
     * 
     * @param string $permission a string to predict user has permission
     * format module_name/feature_name/ability
     * example "lesson/lesson-instructor/create"
     * @return boolean hasPermission
    */
    public function hasPermission(string $permission) {
        $permissions = $this->roles->map(function (Role $role) {
            return $role->permissions;
        })->flatten()->unique();
        [
            $module_name,
            $feature_name,
            $ability,
        ] = explode('/', $permission);
        $hasPermission = $permissions
            ->where('module_name', $module_name)
            ->where('feature_name', $feature_name)
            ->where('ability', $ability)
            ->count() > 0;
        return $hasPermission;
    }
}
